import { defineStore } from "pinia";
import {
  type userType,
  store,
  router,
  resetRouter,
  routerArrays
} from "../utils";
import {
  type UserResult,
  type RefreshTokenResult,
  login,
  logout,
  refreshToken,
  getUserInfo
} from "@/api/user";
import { isString, isArray } from "@pureadmin/utils";
import { useMultiTagsStoreHook } from "./multiTags";
import { useMessage } from "@/hooks/message";
import userDefaultAvatar from "@/assets/cropper_images/user.gif";
import { setToken, removeToken } from "@/utils/auth";
import { closeConnect } from "@/utils/websocket";

export const useUserStore = defineStore({
  id: "pure-user",
  state: (): userType => ({
    userid: "0",
    // 用户名
    username: "",
    // 页面级别权限
    roles: [],
    permissions: [],
    deptid: "0",
    avatar: userDefaultAvatar,
    // 是否勾选了登录页的免登录
    isRemembered: false,
    // 登录页的免登录存储几天，默认7天
    loginDay: 7
  }),
  getters: {
    getUserid: (state: userType) => {
      return state.userid;
    },
    getDeptid: (state: userType) => {
      return state.deptid;
    },
    getUsername: (state: userType) => {
      return state.username;
    },
    getAvatar: (state: userType) => {
      return state.avatar;
    },
    getRoles: (state: userType) => {
      return state.roles;
    },
    getPermissions: (state: userType) => {
      return state.permissions;
    }
  },
  actions: {
    /** 存储头像 */
    SET_AVATAR(avatar: string) {
      this.avatar = avatar;
    },
    SET_USERID(userid: string) {
      this.userid = userid;
      return true;
    },
    SET_DEPTID(deptid: string) {
      this.deptid = deptid;
      return true;
    },
    /** 存储用户名 */
    SET_USERNAME(username: string) {
      this.username = username;
    },

    /** 存储角色 */
    SET_ROLES(roles: Array<string>) {
      this.roles = roles;
    },
    /** 存储按钮级别权限 */
    SET_PERMS(permissions: Array<string>) {
      this.permissions = permissions;
    },
    /** 存储是否勾选了登录页的免登录 */
    SET_ISREMEMBERED(bool: boolean) {
      this.isRemembered = bool;
    },
    /** 设置登录页的免登录存储几天 */
    SET_LOGINDAY(value: number) {
      this.loginDay = Number(value);
    },
    /** 登入 */
    async login(data) {
      return new Promise<UserResult>((resolve, reject) => {
        login(data)
          .then(data => {
            console.log("login", data);
            if (data && data.code === 200) {
              setToken(data.data);
            } else {
              useMessage().error(data.msg);
            }
            resolve(data);
          })
          .catch(error => {
            reject(error);
          });
      });
    },
    /** 前端登出*/
    logOut() {
      logout()
        .then(() => {
          this.SET_USERNAME("");
          this.SET_USERNAME("");
          this.SET_ROLES([]);
          this.SET_PERMS([]);
          this.SET_AVATAR(userDefaultAvatar);
          this.SET_USERID("");
          this.SET_DEPTID("");
          closeConnect();
          removeToken();
          useMultiTagsStoreHook().handleTags("equal", [...routerArrays]);
          resetRouter();
          router.push("/login");
        })
        .catch(() => {
          this.SET_USERNAME("");
          this.SET_USERNAME("");
          this.SET_ROLES([]);
          this.SET_PERMS([]);
          this.SET_AVATAR(userDefaultAvatar);
          this.SET_USERID("");
          this.SET_DEPTID("");
          closeConnect();
          removeToken();
          useMultiTagsStoreHook().handleTags("equal", [...routerArrays]);
          resetRouter();
          router.push("/login");
        });
    },
    async getUserInfo() {
      const res: any = await getUserInfo();
      if (res.code === 200) {
        const data: any = res.data;
        const userid = data.userid;
        const deptid = data.deptid;
        const username = data.username;
        const avatar = data.avatar;
        const roles = data.roles;
        const permissions = data.permissions;
        /**
         * 检验返回数据是否正常，无对应参数，将使用默认用户名,头像,Roles和Permissions
         */
        if (
          (userid && !isString(userid)) ||
          (deptid && !isString(deptid)) ||
          (username && !isString(username)) ||
          (avatar && !isString(avatar)) ||
          (roles && !isArray(roles)) ||
          (permissions && !isArray(permissions))
        ) {
          const err = "getUserInfo核心接口异常，请检查返回JSON格式是否正确";
          useMessage().error(err);
          throw err;
        } else {
          if (userid) this.SET_USERID(userid);
          if (deptid) this.SET_DEPTID(deptid);
          // 如不使用username用户名,可删除以下代码
          if (username) this.SET_USERNAME(username);
          // 如不使用avatar头像,可删除以下代码
          if (avatar) this.SET_AVATAR(avatar);
          // 如不使用roles权限控制,可删除以下代码
          if (roles) this.SET_ROLES(roles);
          // 如不使用permissions权限控制,可删除以下代码
          if (permissions) this.SET_PERMS(permissions);
        }
        return res;
      } else {
        return res;
      }
    },
    /** 刷新`token` */
    async handRefreshToken(data) {
      return new Promise<RefreshTokenResult>((resolve, reject) => {
        refreshToken(data)
          .then(res => {
            if (res.code === 200 && res.data) {
              setToken(res.data);
              resolve(data);
            }
          })
          .catch(error => {
            reject(error);
          });
      });
    },
    async resetAll() {
      this.username = "";
      this.roles = [];
      this.permissions = [];
      this.userid = "";
      this.deptid = "";
      removeToken();
      useMultiTagsStoreHook().handleTags("equal", [...routerArrays]);
      resetRouter();
    }
  }
});

export function useUserStoreHook() {
  return useUserStore(store);
}
